<?php
abstract class system_view_helper_htmlElement extends system_view_helper_abstract {
	const EOL = "\n";
	
	public function getClosingBracket() {
		return ' />';
	}
	protected function _htmlAttribs($attribs) {
		$xhtml = '';
		foreach((array) $attribs as $key => $val) {
			$key = $this->view->escape($key);
			
			if(('on'==substr($key, 0, 2))||('constraints'==$key)) {
				// Don't escape event attributes; _do_ substitute double quotes with singles
				if(!is_scalar($val)) {
					// non-scalar data should be cast to JSON first
					$val = json_encode($val);
				}
				$val = preg_replace('/"([^"]*)":/', '$1:', $val);
			} else {
				if(is_array($val)) {
					$val = implode(' ', $val);
				}
				$val = $this->view->escape($val);
			}
			
			if('id'==$key) {
				$val = $this->_normalizeId($val);
			}
			
			if(strpos($val, '"')!==false) {
				$xhtml .= " $key='$val'";
			} else {
				$xhtml .= " $key=\"$val\"";
			}
		
		}
		return $xhtml;
	}
	
	/**
	 * Normalize an ID
	 *
	 * @param  string $value
	 * @return string
	 */
	protected function _normalizeId($value) {
		if(strstr($value, '[')) {
			if('[]'==substr($value, -2)) {
				$value = substr($value, 0, strlen($value)-2);
			}
			$value = trim($value, ']');
			$value = str_replace('][', '-', $value);
			$value = str_replace('[', '-', $value);
		}
		return $value;
	}
}